package com.server.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;

/**
 * @Description: TODO
 * @Author: mis_wu
 * @Date: 2022/9/14
 **/
@Component("springSessionDefaultRedisSerializer")
public class RedisSessionSerializer extends GenericJackson2JsonRedisSerializer {

    public StringRedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory){
        StringRedisTemplate redisTemplate = new StringRedisTemplate();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        //1、创建jackson序列化方式
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
        //2、创建Object mapper
        ObjectMapper objectMapper = new ObjectMapper();
        //3、允许访问对象中所有属性
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        //4、转换json过程中保存类的信息
        objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance,ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.WRAPPER_ARRAY);
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
        //5、设置key和value的序列化规划  key(String) value(String,list,Set,map)
        StringRedisSerializer hashKeySerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(hashKeySerializer);
        //6、jackson2JsonRedisSerializer就是json序列号规则
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        //6.1 设置hash类型key、value序列化方式
        redisTemplate.setHashKeySerializer(hashKeySerializer);
        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
        //7、工厂创建redisTemplate对象之后再进行配置
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }
}
